/*
 * CollageView.java
 */
package collage;

import java.awt.geom.AffineTransform;
import java.awt.Component;
import java.awt.Graphics2D;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Properties;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JColorChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 * The application's main frame.
 */
public class CollageView extends FrameView {

    public CollageView(SingleFrameApplication app) throws Exception {
        super(app);


        initComponents();            
        
        
        
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

        
        
        // load properties
        props = new Properties();
        File file = new File("props");
        if (!file.exists()) {
            JFileChooser fc = new JFileChooser();
            String myDocs = fc.getCurrentDirectory().getCanonicalPath();
            props.setProperty("importDir", myDocs);
            saveProps();
        }
        props.load(new FileInputStream("props"));

        //create context
        contextMenu = new JPopupMenu();
        
        //add editMenu components to contextMenu and actionToolBar
        for (Component comp: editMenu.getMenuComponents()) {
            if (comp instanceof JMenuItem) {
                JMenuItem menuItem = (JMenuItem) comp;
                //JButton myItem = new JButton(menuItem.getAction());
                //myItem.setBackground(actionToolBar.getBackground());
                contextMenu.add(menuItem.getAction());
                //contextMenu.add(myItem);
                //NOTE: actionToolBar should be horizontally resizable 
                //actionToolBar.add(myItem);
            }
        }


     
       
       

       
        

        

    }

    private void saveProps() throws Exception {
        props.store(new FileOutputStream("props"), null);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = CollageApp.getApplication().getMainFrame();
            aboutBox = new CollageAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        CollageApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        actionToolBar = new javax.swing.JToolBar();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newProjectMenuItem = new javax.swing.JMenuItem();
        openProjectMenuItem = new javax.swing.JMenuItem();
        saveProjectMenuItem = new javax.swing.JMenuItem();
        saveAsImageMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        printPreviewMenuItem = new javax.swing.JMenuItem();
        printMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        importImagesMenuItem = new javax.swing.JMenuItem();
        removeImagesMenuItem = new javax.swing.JMenuItem();
        cropImageMenuItem = new javax.swing.JMenuItem();
        resizeImageMenuItem = new javax.swing.JMenuItem();
        rotateImageMenuItem = new javax.swing.JMenuItem();
        changeColorMenuItem = new javax.swing.JMenuItem();
        bringToFrontMenuItem = new javax.swing.JMenuItem();
        sendToBackMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(collage.CollageApp.class).getContext().getResourceMap(CollageView.class);
        mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                mainPanelShown(evt);
            }
        });

        actionToolBar.setBackground(resourceMap.getColor("actionToolBar.background")); // NOI18N
        actionToolBar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        actionToolBar.setFloatable(false);
        actionToolBar.setRollover(true);
        actionToolBar.setName("actionToolBar"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(actionToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                .addGap(291, 291, 291))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(actionToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(165, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(collage.CollageApp.class).getContext().getActionMap(CollageView.class, this);
        newProjectMenuItem.setAction(actionMap.get("newProject")); // NOI18N
        newProjectMenuItem.setText(resourceMap.getString("newProjectMenuItem.text")); // NOI18N
        newProjectMenuItem.setName("newProjectMenuItem"); // NOI18N
        fileMenu.add(newProjectMenuItem);

        openProjectMenuItem.setAction(actionMap.get("openProject")); // NOI18N
        openProjectMenuItem.setText(resourceMap.getString("openProjectMenuItem.text")); // NOI18N
        openProjectMenuItem.setName("openProjectMenuItem"); // NOI18N
        fileMenu.add(openProjectMenuItem);

        saveProjectMenuItem.setAction(actionMap.get("saveProject")); // NOI18N
        saveProjectMenuItem.setText(resourceMap.getString("saveProjectMenuItem.text")); // NOI18N
        saveProjectMenuItem.setName("saveProjectMenuItem"); // NOI18N
        fileMenu.add(saveProjectMenuItem);

        saveAsImageMenuItem.setAction(actionMap.get("exportAsImage")); // NOI18N
        saveAsImageMenuItem.setText(resourceMap.getString("saveAsImageMenuItem.text")); // NOI18N
        saveAsImageMenuItem.setName("saveAsImageMenuItem"); // NOI18N
        fileMenu.add(saveAsImageMenuItem);

        jSeparator2.setName("jSeparator2"); // NOI18N
        fileMenu.add(jSeparator2);

        printPreviewMenuItem.setIcon(resourceMap.getIcon("printPreviewMenuItem.icon")); // NOI18N
        printPreviewMenuItem.setText(resourceMap.getString("printPreviewMenuItem.text")); // NOI18N
        printPreviewMenuItem.setName("printPreviewMenuItem"); // NOI18N
        fileMenu.add(printPreviewMenuItem);

        printMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        printMenuItem.setIcon(resourceMap.getIcon("printMenuItem.icon")); // NOI18N
        printMenuItem.setText(resourceMap.getString("printMenuItem.text")); // NOI18N
        printMenuItem.setName("printMenuItem"); // NOI18N
        fileMenu.add(printMenuItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
        editMenu.setName("editMenu"); // NOI18N

        importImagesMenuItem.setAction(actionMap.get("importImages")); // NOI18N
        importImagesMenuItem.setName("importImagesMenuItem"); // NOI18N
        editMenu.add(importImagesMenuItem);

        removeImagesMenuItem.setAction(actionMap.get("removeImages")); // NOI18N
        removeImagesMenuItem.setText(resourceMap.getString("removeImagesMenuItem.text")); // NOI18N
        removeImagesMenuItem.setName("removeImagesMenuItem"); // NOI18N
        editMenu.add(removeImagesMenuItem);

        cropImageMenuItem.setAction(actionMap.get("cropImage")); // NOI18N
        cropImageMenuItem.setName("cropImageMenuItem"); // NOI18N
        editMenu.add(cropImageMenuItem);

        resizeImageMenuItem.setAction(actionMap.get("resizeImage")); // NOI18N
        resizeImageMenuItem.setName("resizeImageMenuItem"); // NOI18N
        editMenu.add(resizeImageMenuItem);

        rotateImageMenuItem.setAction(actionMap.get("rotateImage")); // NOI18N
        rotateImageMenuItem.setName("rotateImageMenuItem"); // NOI18N
        editMenu.add(rotateImageMenuItem);

        changeColorMenuItem.setAction(actionMap.get("setBackgroundColor")); // NOI18N
        changeColorMenuItem.setName("changeColorMenuItem"); // NOI18N
        editMenu.add(changeColorMenuItem);

        bringToFrontMenuItem.setAction(actionMap.get("bringToFront")); // NOI18N
        bringToFrontMenuItem.setText(resourceMap.getString("bringToFrontMenuItem.text")); // NOI18N
        bringToFrontMenuItem.setName("bringToFrontMenuItem"); // NOI18N
        editMenu.add(bringToFrontMenuItem);

        sendToBackMenuItem.setAction(actionMap.get("sendToBack")); // NOI18N
        sendToBackMenuItem.setText(resourceMap.getString("sendToBackMenuItem.text")); // NOI18N
        sendToBackMenuItem.setName("sendToBackMenuItem"); // NOI18N
        editMenu.add(sendToBackMenuItem);

        menuBar.add(editMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        jMenuItem1.setAction(actionMap.get("helpButton")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        helpMenu.add(jMenuItem1);

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 235, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void mainPanelShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_mainPanelShown

    // TODO add your handling code here:
    

    
    
}//GEN-LAST:event_mainPanelShown

    @Action
    public void importImages() throws Exception {
        
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new ImageFilter());
        fc.setAcceptAllFileFilterUsed(false);
        fc.setMultiSelectionEnabled(true);
        fc.setCurrentDirectory(new File(props.getProperty("importDir")));
        fc.setApproveButtonText("Import");
        int option = fc.showOpenDialog(canvasPanel);
        if (option == JFileChooser.APPROVE_OPTION) {
            props.setProperty("importDir", fc.getCurrentDirectory().getCanonicalPath());
            saveProps();
            File files[] = fc.getSelectedFiles();
            
            int x = 0, y = 0, maxWidth, maxHeight;
            
            maxWidth = canvasPanel.getWidth()/files.length;
            if(maxWidth < 100) maxWidth = canvasPanel.getWidth()/(int)(canvasPanel.getWidth()/100);
            else if(maxWidth > 300) maxWidth = 300;
            maxHeight = maxWidth*3/2;
            
            for (File f : files) {
                ImagePanel ip = new ImagePanel(f.getCanonicalPath(), maxWidth, maxHeight);
                if(x+ip.getWidth() > canvasPanel.getWidth()) {
                    x = 0;
                    y += maxHeight;
                }
                ip.setLocation(x, y);
                x += ip.getWidth();
                canvasPanel.add(ip);
                
            }
            canvasPanel.repaint();
        }
        
    }

    @Action
    public void newProject() {
        JFrame mainFrame = CollageApp.getApplication().getMainFrame();
        NewProjectBox npb = new NewProjectBox(mainFrame, true); 
        npb.setLocationRelativeTo(mainFrame);
        npb.setVisible(true);
        if(npb.isMakeProj()){    
            if(!createCanvas(npb.getW(), npb.getH())) {
              alert("Selected canvas size is too big. Please select a smaller canvas.");
              newProject();
            }     
            //canvasPanel.removeAll();
            //canvasPanel.setSize(npb.getW(), npb.getH());       
            //canvasPanel.setLocation((mainPanel.getWidth()-canvasPanel.getWidth())/2,(mainPanel.getHeight()-canvasPanel.getHeight())/2);
            //canvasPanel.repaint();   
        }
        //mainPanel.repaint();

    }

    @Action
    public void openProject() {
    }

    @Action
    public void saveProject() {
    }

    @Action
    public void cropImage() {
        ImagePanel selectedImagePanel = getSelectedImagePanel();
        if (selectedImagePanel != null) {
            try {

                BufferedImage img = selectedImagePanel.getOrigImage();

                CropDialog cropDialog = new CropDialog(this.getFrame(), true, img);
                cropDialog.setLocationRelativeTo(this.getFrame());
                cropDialog.setVisible(true);
                BufferedImage croppedImage = cropDialog.getCroppedImage();
                
                if (croppedImage != null) {
                    ImagePanel croppedImagePanel = new ImagePanel(croppedImage, selectedImagePanel.getWidth(), selectedImagePanel.getHeight());
                    croppedImagePanel.setLocation(selectedImagePanel.getLocation());

                    croppedImagePanel.selected = true;
                    canvasPanel.add(croppedImagePanel);
                    canvasPanel.setComponentZOrder(croppedImagePanel, canvasPanel.getComponentZOrder(selectedImagePanel));
                    canvasPanel.remove(selectedImagePanel);
                    canvasPanel.repaint();
                }
            } catch (Exception ex) {
                Logger.getLogger(CollageView.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            // TODO: this shouldn't even occur, the option should be disabled
            alert("Please select at least one image first");
        }

    }
    
    public ImagePanel getSelectedImagePanel() {
            for (Component c : canvasPanel.getComponents()) {
                if (c instanceof ImagePanel) {
                    ImagePanel ip = ((ImagePanel) c);
                    if (ip.selected) {
                        return ip;
                    }
                }
            }
            
            return null;
        
    }
    
    public int getNumSelectedImages() {
        int n = 0;
        
        for (Component c : canvasPanel.getComponents()) 
        {
            if (c instanceof ImagePanel) 
            {
                ImagePanel ip = ((ImagePanel) c);
                if (ip.selected)
                    ++n;
            }
        }  
        return n;
    }

    @Action
    public void resizeImage() {  
        if(getNumSelectedImages() > 0)
        {
            JFrame mainFrame = CollageApp.getApplication().getMainFrame();
            ImageResizeBox irb = new ImageResizeBox(mainFrame,true); 
            irb.setLocationRelativeTo(mainFrame);
            irb.setVisible(true);
            int w, h;
            if(irb.getDoResize() == true) 
            {
                for (Component c : canvasPanel.getComponents()) 
                {
                    if (c instanceof ImagePanel) 
                    {
                        ImagePanel ip = ((ImagePanel) c);
                        if (ip.selected) {  

                                w = Math.round(irb.getPercentageNum()*ip.getWidth()/100);
                                h = Math.round(irb.getPercentageNum()*ip.getHeight()/100);    

                                ip.setSize(w,h);
                                ip.updateImage();
                        }
                    }
                }
                canvasPanel.repaint();
            }
        }
        else
        {
            // TODO: this shouldn't even occur, the option should be disabled
            alert("Please select at least one image first");
        }
    }
    
    void alert(String msg) {
        JOptionPane.showMessageDialog(null,msg);
    }

    @Action
    public void rotateImage() {
       ImagePanel selectedImagePanel = getSelectedImagePanel();
        if (selectedImagePanel != null) {
            try {

                BufferedImage img = selectedImagePanel.getOrigImage();

                        JFrame mainFrame = CollageApp.getApplication().getMainFrame();
                ImageRotateBox irb = new ImageRotateBox(mainFrame, true);
                irb.setLocationRelativeTo(mainFrame);
                irb.setVisible(true);
                BufferedImage rotatedImage = selectedImagePanel.getOrigImage();

                    int angle = irb.getAngle();
                    ImagePanel rotatedImagePanel = new ImagePanel(rotatedImage, selectedImagePanel.getWidth(), selectedImagePanel.getHeight(),angle);
                    rotatedImagePanel.setLocation(selectedImagePanel.getLocation());                    
                    rotatedImagePanel.selected = true;
                    canvasPanel.add(rotatedImagePanel);
                    canvasPanel.setComponentZOrder(rotatedImagePanel, canvasPanel.getComponentZOrder(selectedImagePanel));
                    canvasPanel.remove(selectedImagePanel);                   
                    canvasPanel.repaint();

            } catch (Exception ex) {
                Logger.getLogger(CollageView.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {            
            alert("Please select at least one image first");
        }

    }

    @Action
    public void removeImages() {
        for (Component c : canvasPanel.getComponents()) 
        {
            if (c instanceof ImagePanel) 
            {
                ImagePanel ip = ((ImagePanel) c);
                if (ip.selected) {
                    canvasPanel.remove(ip);
                }
            }
        }
        canvasPanel.repaint();
    }

    @Action
    public void setBackgroundColor() {
        Color newColor = JColorChooser.showDialog(canvasPanel, "Select Color", canvasPanel.getBackground());
        if (newColor != null) {
            canvasPanel.setBackground(newColor);
        }
    }

    @Action
    public void exportAsImage() {
        File fileToSave;
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Save an Image");
        fc.addChoosableFileFilter(new ImageFilter());
        fc.setAcceptAllFileFilterUsed(false);
        fc.setCurrentDirectory(new File(props.getProperty("importDir")));
        fc.setApproveButtonText("Save");
        int option = fc.showOpenDialog(canvasPanel);
        if (option == JFileChooser.APPROVE_OPTION) {
        }
    }

    @Action
    public void bringToFront() {
        ImagePanel selectedImagePanel = getSelectedImagePanel();
        if (selectedImagePanel != null) {
            canvasPanel.setComponentZOrder(selectedImagePanel, 0);
            canvasPanel.repaint();
        } else {
            // TODO: this shouldn't even occur, the option should be disabled
            alert("Please select at least one image first");
        }
    }

    @Action
    public void sendToBack() {
        ImagePanel selectedImagePanel = getSelectedImagePanel();
        if (selectedImagePanel != null) {
            //TODO: make sure mainPanel is ur canvas and it only contains ImagePanel objects
            canvasPanel.setComponentZOrder(selectedImagePanel, canvasPanel.getComponentCount() - 1);
            canvasPanel.repaint();
            
        } else {
            // TODO: this shouldn't even occur, the option should be disabled
            alert("Please select at least one image first");
        }        
    }
    
    public void initActionToolBar() {
        
       
        
        //add editMenu components to actionToolBar
        for (Component comp: editMenu.getMenuComponents()) {
            if (comp instanceof JMenuItem) {
                JMenuItem menuItem = (JMenuItem) comp;
                JButton myItem = new JButton(menuItem.getAction());
                myItem.setBackground(actionToolBar.getBackground());
                //NOTE: actionToolBar should be horizontally resizable 
                actionToolBar.add(myItem);
            }
        }
        
        //TODO: set actionToolBar at center; the following won't work, since a layoutmanager is involved
        actionToolBar.setLocation((mainPanel.getWidth() - actionToolBar.getWidth())/2, 10);

        actionToolBar.setAlignmentX((mainPanel.getWidth() - actionToolBar.getWidth())/2);
        actionToolBar.setAlignmentY((mainPanel.getWidth() - actionToolBar.getWidth())/2);
        
        
        actionToolBar.repaint();
        mainPanel.repaint();
    }
    public void initCanvas() {
       // int x = ((mainPanel.getWidth() - (2 * margin)) - canvasPanel.getWidth()) / 2;
       // int y = ((mainPanel.getHeight() - (2 * margin + actionToolBar.getHeight() + actionToolBar.getX())) - canvasPanel.getHeight()) / 2;

        createCanvas(800, 500);
        
    }
    private boolean createCanvas(int width, int height) {
        
        //create a new canvas
 
        JPanel newCanvasPanel = new JPanel();        
        
        newCanvasPanel.setSize(width, height);
        
        
        int margin = 10;
        int x = (mainPanel.getWidth() - (newCanvasPanel.getWidth() + (2 * margin))) / 2;
        int y = (mainPanel.getHeight() - (newCanvasPanel.getHeight() + (2 * margin) ) ) / 2 + actionToolBar.getHeight() + actionToolBar.getY();
        if (x < 0 || y < 0) {
            
            return false;
        }
        
        //System.out.println("x = " + x + " y = " + y);
        newCanvasPanel.setLocation(x, y);
        
        
        newCanvasPanel.setBackground(Color.WHITE);

        // add listeners
        InputController ic = new InputController(newCanvasPanel, this, contextMenu);
        newCanvasPanel.addMouseListener(ic);
        newCanvasPanel.addMouseMotionListener(ic);
        newCanvasPanel.addKeyListener(ic);
        newCanvasPanel.addMouseWheelListener(ic);
        newCanvasPanel.setFocusable(true);
        
       if (canvasPanel != null) {
            mainPanel.remove(canvasPanel);
        }
        
        mainPanel.add(newCanvasPanel);
        canvasPanel = newCanvasPanel;
        
        canvasPanel.repaint();
        mainPanel.repaint();
        return true;
                        
    }

    @Action
    public void helpButton() {
            if (helpBox == null) {
            JFrame mainFrame = CollageApp.getApplication().getMainFrame();
            helpBox = new HelpBox(mainFrame,true);
            helpBox.setLocationRelativeTo(mainFrame);
        }
        CollageApp.getApplication().show(helpBox);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToolBar actionToolBar;
    private javax.swing.JMenuItem bringToFrontMenuItem;
    private javax.swing.JMenuItem changeColorMenuItem;
    private javax.swing.JMenuItem cropImageMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem importImagesMenuItem;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newProjectMenuItem;
    private javax.swing.JMenuItem openProjectMenuItem;
    private javax.swing.JMenuItem printMenuItem;
    private javax.swing.JMenuItem printPreviewMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem removeImagesMenuItem;
    private javax.swing.JMenuItem resizeImageMenuItem;
    private javax.swing.JMenuItem rotateImageMenuItem;
    private javax.swing.JMenuItem saveAsImageMenuItem;
    private javax.swing.JMenuItem saveProjectMenuItem;
    private javax.swing.JMenuItem sendToBackMenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private JDialog helpBox;
    private Properties props;
    private final JPopupMenu contextMenu;
    private JPanel canvasPanel;
    
}
